<?php
namespace App\Http\Library;

use App\Api\Models\Config;
use App\Http\Library\WeChat\MiniWeChat;
use App\Http\Response\ApiResponse;
use App\Models\CashOrder;
use App\Models\Level;
use App\Models\OrderCommission;
use App\Models\Reply;
use App\Models\ServiceOrder;
use App\Models\User;
use App\Models\Oauth;
use App\Models\UserCard;
use App\Models\UserFollow;
use App\Models\UserLike;
use App\Models\Worker;
use EasyWeChat\Kernel\Exceptions\HttpException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Laravel\Sanctum\Sanctum;

class UserAuth extends ApiResponse
{
    /**
     * @var User|null
     */
    protected ?User $model = null;
    protected ?Request $request = null;

    /**
     * 初始化
     * @param Request $request
     * @param User $user
     */
    public function __construct(Request $request, User $user)
    {
        $this->request = $request;
        $this->model = $user;
    }

    /**
     * 注册
     */
    public function register()
    {
        //注册事件
    }

    /**
     *
     * @param $mobile
     * @param $password
     * @return bool|mixed
     */
    public function login($mobile,$password){
        $auth = User::query()->where('mobile', $mobile)->first();
        if (!$auth){
            return $this->error('找不到此用户！');
        }
        if (!Hash::check($password ,$auth->password)){
            return $this->error('密码不正确,请重试！');
        }
        if ($auth->status==1){
            return $this->error('此账号已被禁用,请联系管理员！');
        }
        $token = $auth->createToken('user')->plainTextToken;
        $userInfo = array_merge(['userInfo'=>$auth->toArray()],['token'=>$token]);
        return $this->success('登陆成功')->data($userInfo);
    }


    /**
     * 微信登陆
     * @param array $post
     */
    public function weChatLogin(array $post = [],Request $request = null)
    {
        try{
            $app = MiniWeChat::instance();
            $res = $app->getCode($post['code']);
        }catch (\Exception $e){
            return $this->error($e->getMessage());
        }
        if(isset($res['errcode'])){
            return $this->error('code ERROR！')->data($res);
        }
        $openid = $res['openid'];
        $session_key = $res['session_key'];
        $oauth = Oauth::findUser('wx_app',$openid);
        if ($oauth){
            $user_id = $oauth['user_id'];
            $oauth->save();
            $user = $this->model->find($user_id);
            if (isset($post['tid'])&&$post['tid']){
                if (!$user->tid){
                    $user->tid = $post['tid'];
                    $user->save();
                }
            }
            $expiration = config("sanctum.expiration");
            if ($expiration){
                $model = new Sanctum::$personalAccessTokenModel;
                $model->where('created_at', '<', now()->subMinutes($expiration + (2 * 60)))->delete();
            }
        }else{
            $user = $this->model->weChatRegister($openid,$post);
            $user_id = $user->id;
        }
        $check = new CheckToken();
        $token = $check->valid($request);
        if (!$token){
            $token = $user->createToken($openid)->plainTextToken;
        }
        $data = [
            'token'=>"Bearer ".$token,
            'session_key'=>$session_key,
            'userInfo'=>$this->getUserInfo($user_id),
        ];
        return $this->success('登陆成功')->data($data);
    }

    /**
     * 获取用户信息
     */
    public function getUserInfo($id)
    {
        $user = User::query()->withCount(['cars','coupons'=>function($query){
            $query->where("status",0)->whereDate("start_time","<=",now())->whereDate("end_time",">=",now());
        }])->withExists(['shop','worker','agent'])->where("id",$id)->first();
        if ($user){
            $user->is_member = UserCard::query()->where("user_id",$user->id)->exists();
            $user->avatar = cdn_url($user->avatar);
            $user->service_order_num = 0;
            if ($user->worker_exists){
                $worker = Worker::getDetail($user->id);
                if ($worker){
                    $shop_id = $worker->shop_id;
                    $user->service_order_num = ServiceOrder::query()->where("worker_id",$worker->id)
                        ->where("status",0)->count() +
                        ServiceOrder::query()->whereIn("shop_id",[0,$shop_id])->where("worker_id",0)
                            ->where("status",0)->count();
                }
            }
            $poster_enter_img = Config::getName("poster_enter_img");
            $user->entry_img = cdn_url($poster_enter_img);
            $user->user_card_num = UserCard::query()
                ->whereDate("start_time","<=",now())
                ->whereDate("end_time",">=",now())
                ->where("user_id",$id)
                ->count();
            $user->wait_amount = OrderCommission::query()->where("top_id",$id)
                ->where("is_settle",0)->sum('top_money')+
                OrderCommission::query()->where("top_top_id",$id)
                ->where("is_settle",0)->sum('top_top_money');
            $user->teams_num = User::query()
                ->whereExists(function ($query) use ($id) {
                    $query->from("payment_orders")->where("pay_status",1)->where("user_id",$id);
                })
                ->where("tid",$id)->count();
            $cash_money = CashOrder::query()->where("status",0)->where("type",3)->where("user_id",$user->id)->sum("amount");
            $user->amount = floatval($user->amount - $cash_money);
            $user->amount = number_format($user->amount,2);
        }
        return $user;
    }

}
